//
//  OAuthViewController.m
//  weibo
//
//  Created by hp on 16/4/28.
//  Copyright © 2016年 hp. All rights reserved.
//

#import "OAuthViewController.h"
#import <AFNetworking.h>
#import "NetworkTools.h"
#import "UserAccount.h"
#define kAppKey @"979703286"
#define kAppSecrect @"1a85c40d724db83b6b937f45499f9ed6"
#define kRedirectURl @"http://www.niit.com.cn"
#import <SVProgressHUD.h>
@interface OAuthViewController ()<UIWebViewDelegate>
@property (nonatomic, strong) UIWebView *webView;
@end

@implementation OAuthViewController

//- (void)loadView
//{
//}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    if ([[UserAccount sharedUserAccount] isLogined]) {
        NSLog(@"已经登录过了");
        return;
    } else {
        [self showLogin];
    }
}


- (void)showLogin
{
    self.webView = [[UIWebView alloc] init];
    self.webView.frame = [UIScreen mainScreen].bounds;
    self.webView.delegate = self;
    [self.view addSubview:self.webView];
    // Do any additional setup after loading the view.
    NSString *apiStr = @"https://api.weibo.com/oauth2/authorize";
    NSString *urlStr = [NSString stringWithFormat:@"%@?client_id=%@&redirect_uri=%@",apiStr,kAppKey,kRedirectURl];
    NSURL *url = [NSURL URLWithString:urlStr];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    [self.webView loadRequest:request];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - webView delegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSLog(@"%@",request.URL.absoluteString);
    NSLog(@"%@",request.URL.query);
//   回调的网址 http://www.niit.com.cn/?code=f8eac8ca61f9dcfee0e2bf2e5fbe733e
    // 如果不是回调的网址都允许跳转
    if (![request.URL.absoluteString hasPrefix:kRedirectURl]) {
        return YES;
    }

    if ([request.URL.query hasPrefix:@"code="]) {
        NSLog(@"授权成功");
//        requestToken 换取Access_Token
        [SVProgressHUD showWithStatus:@"授权成功，正在登陆"];
        [self loadAccessToken:[request.URL.query substringFromIndex:5]];
    } else {
        NSLog(@"授权失败");
    }
    // YES 就是跳转到授权的页面，NO 不跳转
    // 不跳转到回调的网址
    return NO;
}


- (void)loadAccessToken:(NSString *)requestToken
{
    // 请求
    // 1 path
    NSString *urlStr = @"oauth2/access_token";
    // 2 参数
    NSDictionary *dict = @{@"client_id":kAppKey,
                           @"client_secret":kAppSecrect,
                           @"grant_type":@"authorization_code",
                           @"code":requestToken,
                           @"redirect_uri":kRedirectURl};
    
    // 发送请求

    [[NetworkTools sharedNetworkTools] POST:urlStr parameters:dict success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        NSLog(@"%@",dic);
        // 存到UserAccount中
        UserAccount *account = [UserAccount sharedUserAccount];
        [account setValuesForKeysWithDictionary:dic];
        // 设置过期时间
        account.expire_date = [NSDate dateWithTimeInterval:account.expires_in sinceDate:[NSDate date]];
        NSLog(@"过期时间%@",account.expire_date);
        NSLog(@"%@",account);
        // 请求获取用户数据
        [account requestUserInfoSuccessBlock:^(UserAccount *account) {
            NSLog(@"登陆成功过%@",account.screen_name);
            [SVProgressHUD dismiss];
            [self dismissViewControllerAnimated:YES completion:nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationSwitchRootViewController object:nil userInfo:@{@"VC":@"Welcome"}];
        } failedBlock:^(NSError *error) {
            
            NSLog(@"请求数据失败%@",error.localizedDescription);
        }];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error.localizedDescription);
    }];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
